#include <jni.h>
#include "JniLayer.h"
extern "C" {
#include "visual/visual.h"
}

static filter_sys_t* getInstanceInternal(JNIEnv *env, jobject thiz)
{
    auto ptr =  reinterpret_cast<filter_sys_t*>(env->GetLongField(thiz, fields.Spectrum.mInstanceID));
    return ptr;
}

static void
setInstance(JNIEnv *env, jobject thiz, filter_sys_t* mediaPlayer)
{
    env->SetLongField(thiz, fields.Spectrum.mInstanceID, (jlong)(mediaPlayer));
}


extern "C" JNIEXPORT void JNICALL
Java_com_tview_visual_Spectrum_NewInstance(JNIEnv* env,jobject thiz, jint channel, jint branc_80,jint formate) {

    filter_sys_t* system_t = (filter_sys_t *)malloc(sizeof (filter_sys_t)) ;

    system_t->i_nb_chans = channel;
    system_t->i_brand_80 = branc_80;
    system_t->format.format_in = formate;
    system_t->format.format_out = VLC_CODEC_FL32;

    init(system_t);

    setInstance(env,thiz,system_t);
}

extern "C" JNIEXPORT void JNICALL
Java_com_tview_visual_Spectrum_nativeRelease(
        JNIEnv* env,
        jobject thiz/* this */) {

    auto sys = getInstanceInternal( env,thiz);

    delete sys;
}

extern "C" JNIEXPORT int JNICALL
Java_com_tview_visual_Spectrum_nativSetPCM(
        JNIEnv* env,
        jobject thiz/* this */, jbyteArray data,jint nb_sample, jintArray ints) {

    auto sys = getInstanceInternal( env,thiz);

    uint8_t * pcmBuffer = NULL;
    pcmBuffer = (uint8_t *)env->GetByteArrayElements(data, NULL);
    if (pcmBuffer == NULL) {
        return -1;
    }

    int *c_array;
    jint len_arr;

    //1. 获取数组长度
    len_arr = env->GetArrayLength(ints);

    //2. 申请缓冲区
    c_array = (int *) malloc(sizeof(int) * len_arr);

//    int *arrPointer = reinterpret_cast<int *>(*env->GetIntArrayElements(ints, NULL));

    jsize  oldsize =env->GetArrayLength(data);

    block_t block;
    block.need_release = no_release;
    block.i_buffer = nb_sample*2;
    block.p_buffer = pcmBuffer;
    block.i_nb_samples = nb_sample;

    block_t* ret = DoWork(sys, &block, c_array);

    env->SetIntArrayRegion(ints, 0, len_arr, c_array);

    block_Release(ret);

    return 1;

}